package com.hhxy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hhxy.common.R;
import com.hhxy.entiy.User;
import com.hhxy.service.UserService;
import com.hhxy.utils.ValidateCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
@Api(tags = "用户的登录和管理请求")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value = "获取验证码",notes = "模拟六位数的短信验证码")
    @PostMapping("sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("验证码={}",code);

            session.setAttribute(phone,code);
            return R.success("手机验证码发送成功！");
        }
        return R.error("手机验证码发送失败！");
    }

    @ApiOperation(value = "用户登录",notes = "手机号和短信验证码登录")
    @PostMapping("login")
    public R<User> login(@RequestBody Map map,HttpSession session) {

        String phone = map.get("phone").toString();
        String code = map.get("code").toString();
        Object attribute = session.getAttribute(phone);
        if (attribute != null && attribute.equals(code)) {
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);

            if (user == null) {
                user.setPhone(phone);
                user.setRole(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
//            BaseContext.setCurrentId((Integer) session.getAttribute("user"));
            return R.success(user);
        }
        return R.error("登录失败！");
    }

    @GetMapping("getById")
    public R<User> getById(HttpSession session) {
//        log.info("登录用户id={}",BaseContext.getCurrentId());
        return R.success(userService.getById(1));
    }

}
